﻿using DotNet.Utilities;
using JinfuyuanProject.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Security.Cryptography;
using DocumentFormat.OpenXml.Spreadsheet;
using Pages = JinfuyuanProject.Entity.Pages;
using JinfuyuanProject.Entity.ViewModels;
using JinfuyuanProject.Service.Interface;
using JinfuyuanProject.Entity.Filter;

namespace JinfuyuanProject.Service.Service
{
    public class LoginService : ILoginService
    {
        private readonly JinfuyuanDbContext _db;
        private readonly ISalaryService _salaryService;
        private readonly SalaryFilter _filter;

        public LoginService(JinfuyuanDbContext jinfuyuanDbContext,ISalaryService salaryService,SalaryFilter filter) { 
        _db = jinfuyuanDbContext;
            // 这里可以使用 salaryService 进行其他操作
            _salaryService = salaryService;
            _filter = filter;
        }
        public ResMessage CheckLogin(string account, string password)
        {

            // 创建默认的返回消息
            ResMessage ht = ResMessage.Success(new Staff());

            // 判断账号或密码是否为空
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
            {
                ht.code = 1;
                ht.msg = "用户名或密码不能为空";
                return ht;
            }

            // 查找数据库中对应的员工信息
            Staff staff = _db.Staff.Where(u => u.Numbers == account &&u.Pwd==password).FirstOrDefault();
            if (staff == null)
            {
                ht.code = 1;
                ht.msg = "用户名或密码错误或员工已停用";
                return ht;
            }
            staff= _db.Staff.Where(u => u.Numbers == account && u.Pwd == password).Where(u => u.State==0).FirstOrDefault();
            if (staff == null)
            {
                ht.code = 1;
                ht.msg = "员工已停用";
                return ht;
            }
            // 设置登录成功后的返回数据
            ht.code = 0;
            ht.data = staff;
            // 将用户信息存储到 Session
            HttpContext.Current.Session["user"] = staff;

            var page_id_list = _db.RoleAndPage.Where(x => x.RoleId == staff.RoleId).ToList()
                   .Join(_db.Pages, r => r.PageId, p => p.Id, (r, p) => new Pages
                   {
                       Id = p.Id,
                       ModuleId = p.ModuleId,
                       PageName = p.PageName,
                       PageUrl = p.PageUrl,
                       CreateTime = p.CreateTime,
                       Isdelete = p.Isdelete
                   }).ToList();
            var all_page_list = _db.Pages.Select(p => p.PageUrl.ToLower()).ToList();
            HttpRuntime.Cache.Insert("all_page_list", all_page_list, null, DateTime.MaxValue, TimeSpan.FromDays(1));

            var url_list = page_id_list
                            .Where(p => p.Isdelete == 0)
                            .Select(p => p.PageUrl.ToLower())
                            .ToList();

            HttpRuntime.Cache.Insert(staff.Id.ToString(), url_list, null, DateTime.MaxValue, TimeSpan.FromDays(1));
            bool isFirstLogin = false;
            HttpCookie firstLoginCookie1 = HttpContext.Current.Request.Cookies["isFirstLogin"+staff.Numbers];
            //if (HttpContext.Current.Request.Cookies["isFirstLogin"] != null)
            //{
            //    firstLoginCookie1.Expires = DateTime.Now.AddDays(-1); // 删除 Cookie
            //    HttpContext.Current.Response.Cookies.Add(firstLoginCookie1); // 删除 Cookie
            //}
            // 检查 Cookie 中是否有首次登录的标志
            if (HttpContext.Current.Request.Cookies["isFirstLogin"+staff.Numbers] == null)
            {
                isFirstLogin = true;
                HttpCookie firstLoginCookie = new HttpCookie("isFirstLogin" + staff.Numbers, "true");
                // 获取当前日期的第二天的早上8点
                DateTime expireDate = DateTime.Today.AddDays(1).AddHours(8);
                // 设置 Cookie 的过期时间为第二天早上8点
                firstLoginCookie.Expires = expireDate;
                HttpContext.Current.Response.Cookies.Add(firstLoginCookie); // 设置 Cookie
            }

            if (isFirstLogin)
            {
                _filter.EmpId = staff.Id;
                Salary salary = _salaryService.Query(_filter);
                if (salary != null&&salary.CreateTime.Value.Month==DateTime.Now.Month)
                {
                    salary.WorkDays += 1;
                    _salaryService.Update(salary);
                }
                else
                {
                    salary = new Salary
                    {
                        EmpId = staff.Id,
                        WorkDays = 1,
                        BaseSalary = 0,
                        ExtraSaraly = 0,
                        TotalSaraly = 0,
                        CreateTime = DateTime.Now
                    };
                    _salaryService.Insert(salary);
                }
            }
            return ht;
        }
        public List<ModuleVM> GetMenuForRole(int roleId)
        {
            // 判断角色ID是否有效
            if (roleId == 0)
            {
                return null; // 或者抛出一个异常
            }

            // 获取该角色拥有的页面列表
            var pageIdList = _db.RoleAndPage
                .Where(x => x.RoleId == roleId)
                .Join(_db.Pages, r => r.PageId, p => p.Id, (r, p) => p)
                .Distinct()
                .ToList();

            // 获取所有模块
            List<Modules> moduleList = _db.Modules.ToList();

            // 获取该角色可以访问的模块
            var modules = moduleList.Where(m => pageIdList.Any(p => p.ModuleId == m.Id)).Distinct().ToList();

            List<ModuleVM> result = new List<ModuleVM>();

            foreach (var m in modules)
            {
                var vm = new ModuleVM
                {
                    id = m.Id,
                    mname = m.ModuleName,
                    create_time = m.CreateTime,
                    icon = "layui-icon layui-icon-console",
                    title = m.ModuleName,
                    type = 0,
                    children = new List<PageVM>()
                };

                var pages = pageIdList.Where(p => p.ModuleId == m.Id && p.Isdelete == 0 && p.Type == 1)
                                      .GroupBy(p => p.Id)
                                      .Select(g => g.First())
                                      .ToList();

                foreach (var p in pages)
                {
                    vm.children.Add(new PageVM
                    {
                        id = p.Id + 20,
                        page_name = p.PageName,
                        create_time = p.CreateTime,
                        href = p.PageUrl,
                        icon = "layui-icon layui-icon-console",
                        openType = "_component",
                        title = p.PageName,
                        type = 1,
                        url = p.PageUrl,
                        mid = (int)p.ModuleId,
                    });
                }

                result.Add(vm);
            }

            return result;
        }
    }
}
